// 扩展 day.js 插件
dayjs.extend(dayjs_plugin_utc)
dayjs.extend(dayjs_plugin_timezone)

/* 支付模块 */

const payApiPath = '/api/pay/'

const $paymentOptions = $('#paymentOptions')
const $shoppingName = $('#shoppingName')

const $easyPayUrl = $('#easyPayUrl')
const $easyPayid = $('#easyPayid')
const $easyPaykey = $('#easyPaykey')

const $appId = $('#appId')
const $privateKey = $('#privateKey')
const $alipayPublicKey = $('#alipayPublicKey')

// 渲染数据
const renderingPayData = async () => {
	try {
		const response = await fetch(`${payApiPath}getConfig`)
		const { code, msg, data } = await response.json()

		if (code !== 200) {
			showNotify(msg, 'warning', 5000, 'mdi mdi-alert', 'top', 'right')
			return
		}

		const { config, easyPay, Alipay } = data

		const { channel, shoppingName } = config._children
		$(`#${channel}`).prop('selected', true)
		$shoppingName.val(shoppingName)

		const { easyPayUrl, easyPayid, easyPaykey } = easyPay._children
		$easyPayUrl.val(easyPayUrl)
		$easyPayid.val(easyPayid)
		$easyPaykey.val(easyPaykey)
		
		const { appId, privateKey, alipayPublicKey } = Alipay._children
		$appId.val(appId)
		$privateKey.val(privateKey)
		$alipayPublicKey.val(alipayPublicKey)
	} catch (error) {
		showNotify('服务器有误', 'danger', 5000, 'mdi mdi-alert', 'top', 'right')
	}
}

// 保存支付
async function savePayData() {
	const paymentOptions = $paymentOptions.val()
	const shoppingName = $shoppingName.val()
	const easyPayUrl = $easyPayUrl.val()
	const easyPayid = $easyPayid.val()
	const easyPaykey = $easyPaykey.val()
	const appId = $appId.val()
	const privateKey = $privateKey.val()
	const alipayPublicKey = $alipayPublicKey.val()

	if (!paymentOptions) {
		showNotify('支付选项不得为空', 'warning', 5000, 'mdi mdi-alert', 'top', 'right')
		return
	}

	const data = {
		channel: paymentOptions,
		shoppingName: shoppingName || null,
		easyPayUrl: easyPayUrl || null,
		easyPayid: easyPayid || null,
		easyPaykey: easyPaykey || null,
		appId: appId || null,
		privateKey: privateKey || null,
		alipayPublicKey: alipayPublicKey || null
	}

	const options = {
		method: 'POST',
		headers: {
		  'Content-Type': 'application/json'
		},
		body: JSON.stringify(data)
	}

	try {
		const response = await fetch(`${payApiPath}setConfig`, options)
		const { code, msg } = await response.json()
		
		if (code !== 200) {
			showNotify(msg, 'warning', 5000, 'mdi mdi-alert', 'top', 'right')
			return
		}

		showNotify(msg, 'success', 5000, 'mdi mdi-check-circle', 'top', 'right')
		renderingPayData()
	} catch (error) {
		showNotify('服务器有误', 'danger', 5000, 'mdi mdi-alert', 'top', 'right')
	}
}


/* 赞助列表数据 */

const sponsorApiPath = '/api/sponsor/'

const $sponsorData = $('#sponsorData')
const $paginationDom = $('#paginationDom')
const $loadingDom = $('#loading-dom')

// 渲染表格
const renderingTable = async (data, page, pageSize) => {
	let tr = ''

	if (data.length < 1) {
		$loadingDom.hide()
		$sponsorData.html('<tr><td colspan="9" class="text-center">无人打赏...</td></tr>')
		return
	}
		
	data.forEach(item => {
		// 时间戳转换
		const formattedTime = dayjs(Number(item.orders)).format('YYYY年MM月DD日 HH:mm:ss')

		tr += `<tr class="text-center align-middle">
			<td>${item.id}</td>
			<td>
				<img class="lazyload" data-src="https://q.qlogo.cn/headimg_dl?dst_uin=${item.qq}&spec=100&img_type=png" style="max-width: 45px; border-radius: 50%; border: 1px solid #ccc">
			</td>
			<td data-bs-toggle="tooltip" data-bs-placement="top" title="${item.name}">
				<span class="d-inline-block text-truncate" style="max-width: 100px;">${item.name}</span>
			</td>
			<td>${item.qq}</td>
			<td>
				${item.payStatus === '1'
					? `<span class="link-primary fw-bolder">${item.amount}元</span>`
					: `<span class="link-secondary" style="opacity: .5;">${item.amount}元</span>`
				}
			</td>
			<td>
				${item.payStatus === '1'
					? '<span class="badge bg-primary bg-gradient fw-bolder">已付款</span>'
					: '<span class="badge bg-secondary bg-gradient">未付款</span>'
				}
			</td>
			<td>${formattedTime}</td>
			<td>${item.orders}</td>
			<td>
				<div class="btn-group btn-group-sm">
					<a class="btn btn-default" href="JavaScript:;" data-bs-toggle="tooltip" onclick="setTr(${item.id}, '${page}', '${pageSize}')" title="编辑">
						<i class="mdi mdi-pencil"></i>
					</a>
					<a class="btn btn-default" href="JavaScript:;" data-bs-toggle="tooltip" onclick="delTr('id', ${item.id}, '${page}', '${pageSize}')" title="删除">
						<i class="mdi mdi-window-close"></i>
					</a>
				</div>
			</td>
		</tr>`
	})

	$sponsorData.html(tr)
	tr = null
	$loadingDom.hide()
	// 渲染工具
	renderTooltip()
	$('.lazyload').lazyload({
		root: null,
		rootMargin: '50px',
		threshold: 0
	})
}

// 渲染数据
const renderingSponsorData = async (page = 1, pageSize = 10) => {
	// 遮罩
	$loadingDom.lyearloading({
		opacity: 0.5,
		backgroundColor: '#ccc',
		textColorClass: 'text-info',
		spinnerColorClass: 'text-info',
		spinnerSize: 'lg',
		spinnerText: '加载中...',
		zindex: 9999
	})

	try {
		const response = await fetch(`${sponsorApiPath}get?page=${page}&pageSize=${pageSize}`)
		const result = await response.json()
		if (result.code !== 200) {
			$sponsorData.html(`<tr><td colspan="9" class="text-center">${result.msg}</td></tr>`)
			return
		}
		const { data, total } = result.data

		renderingTable(data, page, pageSize)

		// 渲染分页
		renderingPagination(total, Number(page), Number(pageSize))
	} catch (error) {
		$sponsorData.html('<tr><td colspan="9" class="text-center">服务器有误</td></tr>')
		showNotify('服务器有误', 'danger', 5000, 'mdi mdi-alert', 'top', 'right')
	}
}

// 渲染分页
function renderingPagination(total, page, limit) {
	// 计算总页数
	const totalPage = Math.ceil(total / limit)
	
	let li = ''
	if (page > 1) {
		li += `<li class="page-item"><a class="page-link" href="JavaScript:;" onclick="renderingSponsorData(${page - 1}, ${limit})">上一页</a></li>`
	} else {
		li += `<li class="page-item disabled"><span class="page-link">上一页</span></li>`
	}
	for (let i = 1; i <= totalPage; i++) {
		if (i === page) {
			li += `<li class="page-item active"><span class="page-link">${i}</span></li>`
		} else {
			li += `<li class="page-item"><a class="page-link" href="JavaScript:;" onclick="renderingSponsorData(${i}, ${limit})">${i}</a></li>`
		}
	}
	if (page < totalPage) {
		li += `<li class="page-item"><a class="page-link" href="JavaScript:;" onclick="renderingSponsorData(${page + 1}, ${limit})">下一页</a></li>`
	} else {
		li += `<li class="page-item disabled"><span class="page-link">下一页</span></li>`
	}
	$paginationDom.html(li)
	li = null
}

// 新增
function add() {
	$.confirm({
		title: '新增赞助',
		type: 'blue',
		animation: 'scale',
		draggable: true,
		content: `
			<div class="form-group p-1 mb-0">
				<label class="control-label mb-1">名称</label>
				<div class="input-group">
					<input autofocus="" type="text" id="input-name" placeholder="请输入赞助名称" class="form-control" autocomplete="off">
				</div>
			</div>
			<div class="form-group p-1 mb-0">
				<label class="control-label mb-1">QQ</label>
				<div class="input-group">
					<input autofocus="" type="number" id="input-qq" placeholder="请输入赞助QQ号" class="form-control" autocomplete="off">
				</div>
			</div>
			<div class="form-group p-1 mb-0">
				<label class="control-label mb-1">赞助金额</label>
				<div class="input-group">
					<input autofocus="" type="number" id="input-amount" placeholder="请输入赞助金额" class="form-control" autocomplete="off">
				</div>
			</div>
			<div class="form-group p-1 mb-0">
				<label class="control-label mb-1 payStatus">付款状态</label>
				<select class="form-control selectpicker" name="payStatus" id="payStatus">
					<option value="1">已付款</option>
					<option value="0">未付款</option>
				</select>
			</div>	
		`,
		buttons: {
			submit: {
				text: '提交',
				btnClass: 'btn-primary',
				action: function () {
					let that = this

					const name = that.$content.find('#input-name').val()
					const qq = that.$content.find('#input-qq').val()
					const amount = that.$content.find('#input-amount').val()
					const payStatus = that.$content.find('#payStatus').val()

					const data = {
						name,
						qq,
						amount,
						payStatus
					}
					if (!$.trim(name) || !$.trim(qq) || !$.trim(amount) || !$.trim(payStatus)) {
						$.alert({
							title: '',
							content: '参数不得为空',
							type: 'orange'
						})
						return false
					}

					$.ajax({
						url: sponsorApiPath + 'add',
						type: 'POST',
						data,
						success: function (response) {
							const { code, msg } = response
							if (code !== 200) {
								$.alert({
									title: '',
									content: msg,
									type: 'orange'
								})
								return
							}
							$.alert({
								title: '',
								content: msg,
								type: 'green'
							})
							renderingSponsorData()
						}
					})
				}
			},
			'取消': function () { }
		}
	})
}

// 更新
async function setTr(id, page = 1, pageSize = 10) {
	if (!id) {
		showNotify('参数不得为空', 'warning', 5000, 'mdi mdi-alert', 'top', 'right')
		return
	}

	try {
		const response = await fetch(`${sponsorApiPath}query?id=${id}`)
		const result = await response.json()
		if (result.code !== 200) {
			showNotify(result.msg, 'warning', 5000, 'mdi mdi-alert', 'top', 'right')
			return
		}

		const arrayData = result.data
		if (arrayData.length < 1) {
			showNotify('未查询到此参数', 'warning', 5000, 'mdi mdi-alert', 'top', 'right')
			return
		}

		const obj = arrayData[0]

		$.confirm({
			title: '更新赞助',
			type: 'blue',
			animation: 'scale',
			draggable: true,
			content: `
				<div class="form-group p-1 mb-0">
					<label class="control-label mb-1">名称</label>
					<div class="input-group">
						<input autofocus="" type="text" id="input-name" placeholder="请输入赞助名称" value="${obj.name}" class="form-control" autocomplete="off">
					</div>
				</div>
				<div class="form-group p-1 mb-0">
					<label class="control-label mb-1">QQ</label>
					<div class="input-group">
						<input autofocus="" type="number" id="input-qq" placeholder="请输入赞助QQ号" value="${obj.qq}" class="form-control" autocomplete="off">
					</div>
				</div>
				<div class="form-group p-1 mb-0">
					<label class="control-label mb-1">赞助金额</label>
					<div class="input-group">
						<input autofocus="" type="number" id="input-amount" placeholder="请输入赞助金额" value="${obj.amount}" class="form-control" autocomplete="off">
					</div>
				</div>
				<div class="form-group p-1 mb-0">
					<label class="control-label mb-1 payStatus">付款状态</label>
					<select class="form-control selectpicker" name="payStatus" id="payStatus">
						<option value="1" ${obj.payStatus === '1' ? 'selected' : ''}>已付款</option>
						<option value="0" ${obj.payStatus === '0' ? 'selected' : ''}>未付款</option>
					</select>
				</div>	
			`,
			buttons: {
				submit: {
					text: '更新',
					btnClass: 'btn-primary',
					action: function () {
						let that = this
	
						const name = that.$content.find('#input-name').val()
						const qq = that.$content.find('#input-qq').val()
						const amount = that.$content.find('#input-amount').val()
						const payStatus = that.$content.find('#payStatus').val()
	
						const data = {
							id,
							name,
							qq,
							amount,
							payStatus
						}
						if (!$.trim(id) || !$.trim(name) || !$.trim(qq) || !$.trim(amount) || !$.trim(payStatus)) {
							$.alert({
								title: '',
								content: '参数不得为空',
								type: 'orange'
							})
							return false
						}
	
						$.ajax({
							url: sponsorApiPath + 'set',
							type: 'POST',
							data,
							success: function (response) {
								const { code, msg } = response
								if (code !== 200) {
									$.alert({
										title: '',
										content: msg,
										type: 'orange'
									})
									return
								}
								$.alert({
									title: '',
									content: msg,
									type: 'green'
								})
								renderingSponsorData(page, pageSize)
							}
						})
					}
				},
				'取消': function () { }
			}
		})
	} catch (error) {
		showNotify('获取失败', 'danger', 5000, 'mdi mdi-alert', 'top', 'right')
	}
}

// 删除
async function delTr(k, val, page = 1, pageSize = 10) {
	if (!k || !val) {
		showNotify('参数不得为空', 'warning', 5000, 'mdi mdi-alert', 'top', 'right')
		return
	}

	if (k !== 'id' && k !== 'payStatus' && k !== 'all') {
		showNotify('参数有误', 'warning', 5000, 'mdi mdi-alert', 'top', 'right')
		return
	}

	try {
		const isDel = await swal({
			title: '确定删除这个订单吗?',
			text: '',
			icon: 'warning',
			buttons: ['取消', '确定'],
			dangerMode: true
		})

		if(!isDel) {
			return
		}

		const response = await fetch(`${sponsorApiPath}del?${k}=${val}`)
		const result = await response.json()
		if (result.code !== 200) {
			showNotify(result.msg, 'warning', 5000, 'mdi mdi-alert', 'top', 'right')
			return
		}
		showNotify(result.msg, 'success', 5000, 'mdi mdi-check-circle', 'top', 'right')
		renderingSponsorData(page, pageSize)
	} catch (error) {
		showNotify('服务器有误', 'danger', 5000, 'mdi mdi-alert', 'top', 'right')
	}
}

// 查询
function querySponsor() {
	$.confirm({
		title: '查询赞助',
		type: 'dark',
		icon: 'mdi mdi-magnify',
		animation: 'scale',
		draggable: true,
		content: `
			<div class="form-group p-1 mb-0">
				<label class="control-label mb-1 queryCriteria">查询条件</label>
				<select class="form-control selectpicker" name="queryCriteria" id="queryCriteria">
					<option value="id">编号查询</option>
					<option value="qq">QQ号查询</option>
					<option value="orders">订单查询</option>
				</select>
			</div>
			<div class="form-group p-1 mb-0">
				<label class="control-label mb-1">查询数据</label>
				<div class="input-group">
					<input autofocus="" type="text" id="input-data" placeholder="请输入值" class="form-control" autocomplete="off">
				</div>
			</div>
		`,
		buttons: {
			submit: {
				text: '查询',
				btnClass: 'btn-primary',
				action: function () {
					let that = this

					const data = that.$content.find('#input-data').val()
					const queryCriteria = that.$content.find('#queryCriteria').val()

					if (!$.trim(data) || !$.trim(queryCriteria)) {
						$.alert({
							title: '',
							content: '参数不得为空',
							type: 'orange'
						})
						return false
					}

					$.ajax({
						url: `${sponsorApiPath}query?${queryCriteria}=${data}`,
						type: 'GET',
						success: function (response) {
							const { code, msg, data } = response
							if (code !== 200) {
								$.alert({
									title: '',
									content: msg,
									type: 'orange'
								})
								$sponsorData.html(`<tr><td colspan="9" class="text-center">${msg}</td></tr>`)
								return
							}

							// 遮罩
							$loadingDom.lyearloading({
								opacity: 0.5,
								backgroundColor: '#ccc',
								textColorClass: 'text-info',
								spinnerColorClass: 'text-info',
								spinnerSize: 'lg',
								spinnerText: '加载中...',
								zindex: 9999
							})

							renderingPagination(data.length, 1, 1000000)
							if (data.length < 1) {
								$sponsorData.html('<tr><td colspan="9" class="text-center">未查询到数据</td></tr>')
								$loadingDom.hide()
								return
							}
							renderingTable(data, 1, 1000000)
						}
					})
				}
			},
			'取消': function () { }
		}
	})
}

// 状态查询
function queryPayStatus(status = '1') {
	if (status !== '0' && status !== '1') {
		$sponsorData.html('<tr><td colspan="9" class="text-center">查询有误</td></tr>')
		return
	}
	// 遮罩
	$loadingDom.lyearloading({
		opacity: 0.5,
		backgroundColor: '#ccc',
		textColorClass: 'text-info',
		spinnerColorClass: 'text-info',
		spinnerSize: 'lg',
		spinnerText: '加载中...',
		zindex: 9999
	})
	$.ajax({
		url: `${sponsorApiPath}query?payStatus=${status}`,
		type: 'GET',
		success: function (response) {
			const { code, msg, data } = response
			if (code !== 200) {
				$.alert({
					title: '',
					content: msg,
					type: 'orange'
				})
				$sponsorData.html(`<tr><td colspan="9" class="text-center">${msg}</td></tr>`)
				$loadingDom.hide()
				return
			}

			renderingPagination(data.length, 1, 1000000)
			if (data.length < 1) {
				$sponsorData.html('<tr><td colspan="9" class="text-center">未查询到数据</td></tr>')
				$loadingDom.hide()
				return
			}
			renderingTable(data, 1, 1000000)
		}
	})
}


/* 模块数据 */

// 获取模块信息
function getModuleInfo() {
	$.ajax({
		url: sponsorApiPath + 'getModuleInfo',
		type: 'GET',
		success: function (response) {
			const { code, msg, data } = response
			if (code !== 200) {
				showNotify(msg, 'warning', 5000, 'mdi mdi-alert', 'top', 'right')
				return
			}

			const { sponsor_title, sponsor_desc, sponsor_list_title, sponsor_btn_text, sponsor_list_icon, sponsor_home_icon } = data

			$('#sponsor_title').val(sponsor_title)
			$('#sponsor_desc').val(sponsor_desc)
			$('#sponsor_list_title').val(sponsor_list_title)
			$('#sponsor_btn_text').val(sponsor_btn_text)
			$('#sponsor_list_icon').val(sponsor_list_icon)
			$('#sponsor_home_icon').val(sponsor_home_icon)
		}
	})
}

// 保存模块信息
function saveSponsorData() {
	const sponsor_title = $('#sponsor_title').val()
	const sponsor_desc = $('#sponsor_desc').val()
	const sponsor_list_title = $('#sponsor_list_title').val()
	const sponsor_btn_text = $('#sponsor_btn_text').val()
	const sponsor_list_icon = $('#sponsor_list_icon').val()
	const sponsor_home_icon = $('#sponsor_home_icon').val()

	if (!$.trim(sponsor_list_icon) || !$.trim(sponsor_home_icon)) {
		showNotify('图标参数不得为空', 'warning', 5000, 'mdi mdi-alert', 'top', 'right')
		return
	}

	const data = {
		sponsor_title,
		sponsor_desc,
		sponsor_list_title,
		sponsor_btn_text,
		sponsor_list_icon,
		sponsor_home_icon
	}

	const options = {
		method: 'POST',
		headers: {
		  'Content-Type': 'application/json'
		},
		body: JSON.stringify(data)
	}

	fetch(`${sponsorApiPath}setModuleInfo`, options)
		.then(response => response.json())
		.then(result => {
			if (result.code !== 200) {
				showNotify(result.msg, 'warning', 5000, 'mdi mdi-alert', 'top', 'right')
				return
			}
			
			showNotify(result.msg, 'success', 5000, 'mdi mdi-check-circle', 'top', 'right')
			getModuleInfo()
		})
		.catch(error => {
			showNotify('服务器有误', 'danger', 5000, 'mdi mdi-alert', 'top', 'right')
		})
}


// 立即执行
(() => {
	$('input, textarea').attr('autocomplete', 'off')

	renderingPayData()
	getModuleInfo()
	renderingSponsorData()

	const $paymentRecommendation = $('#paymentRecommendation')

	$.ajax({
		type: 'GET',
		url: 'https://www.xfabe.com/nitaiv5pro/',
		data: {
			paymentRecommendation: '1'
		},
		dataType: 'JSON',
		success: res => {
			const { code, msg, data } = res
			if (code !== 200) {
				showNotify(msg, 'danger', 5000, 'mdi mdi-alert', 'top', 'right')
				return
			}

			if (data.length < 1) {
				return
			}
			let a = ''
			data.forEach(item => {
				a += `<a href="${item.link}" class="badge bg-success link-light fw-bolder" target="_blank" rel="noopener noreferrer">${item.text}</a>`
			})

			$paymentRecommendation.html(a)
			a = null
		},
		error: () => {
			showNotify('API有误', 'danger', 5000, 'mdi mdi-alert', 'top', 'right')
		}
	})
})()